<template>
  <div>
    <el-dialog v-model="dialogFormVisible" :title="title" destroy-on-close>
      <el-form ref="ruleFormRef" :model="form" label-width="150" style="padding: 0px 15px" status-icon dis>
        <el-form-item :label="name.enterpriseCode" prop="enterpriseCode">
          <el-input v-model="form.enterpriseCode" disabled="disabled"/>
        </el-form-item>
        <el-form-item prop="collectitemName" :label="name.collectitemName">
          <el-input v-model="form.collectitemName" disabled="disabled"/>
        </el-form-item>
        <el-form-item prop="dataCode" :label="name.dataCode">
          <el-input v-model="form.dataCode" disabled="disabled"/>
        </el-form-item>
        <el-form-item prop="equipmentCode" label="映射值:">
          <!--项目分析列表-->
          <el-select v-model="form.mappingValue" v-if="form.equipmentCode === '00'" filterable >
            <el-option v-for="item in options" :key="item.key" :value="item.value" :label="item.value"/>
          </el-select>
          <!--设备分析列表-->
          <el-select v-if="form.equipmentCode !== '00'" v-model="form.deviceName" placeholder="请选择设备"
                      @change="deviceChange" filterable >
            <el-option-group v-for="group in emitData.deviceOption" :key="group.region" :label="group.region">
              <el-option v-for="item in group.device" :key="item.deviceId" :label="item.name"
                         :value="item.deviceId"/>
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.equipmentCode!== '00' && form.deviceName !== null" prop="equipmentCode">
          <!--设备分析名称-->
          <el-select v-model="form.mappingValue" filterable >
            <el-option v-for="item in deviceOptions" :key="item.key" :value="item.value" :label="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item style="width: 100%; margin-left: 0px">
          <div>
            <el-button type="info" @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
            <el-button
                type="danger"
                ref="buttonRefs"
                @click="open"
            >删除</el-button
            >
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import {reactive, ref} from "vue";
import mitts from "@/utils/bus.js";
import {
  getNameList,
  getProjectAnaListBypProjectId,
  saveDataCodeAnalyzeMapping,
  getDataCodeAnalyzeMapping,
  delDataCodeAnalyzeMapping,
  getDeviceAnaListByDeviceId
} from "@/api/enterprise/index.js";
import {selectB} from "@/api/enterpriseArchives/index.js";
import {ElMessage, ElMessageBox} from "element-plus";

const dialogFormVisible = ref(false);
const title = ref("数据映射");
const ruleFormRef = ref();
const isEdit = ref(false);
const options = ref([])
const deviceOptions = ref([])
const deviceOption = ref([]);
const equipmentNameIdMap = reactive({
  baseData : {}
});
const emitData = reactive({
  //控件传入参数
  formulaOption: [],
  deviceOption: [],
  topOptions: [],
  dataId: "",
});
let formInline = reactive({
  region: "0",
  id: "",
  name: "",
  weight: "",
  label: "",
});

let form = reactive({
  dataId: "", //主键
  enterpriseCode: "", //统一社会信用代码
  collectitemName: "", //采集数据项指标名称
  dataCode: "", //采集数据项编码
  equipmentCode: "", //重点设备类型
  mappingValue: "", //映射值(分析项名称)
  deviceName: "", //设备名称
});
const name = {
  dataId: "主键", //主键
  enterpriseCode: "统一社会信用代码:", //统一社会信用代码
  collectitemName: "采集数据项指标名称:", //采集数据项指标名称
  dataCode: "采集数据项编码:", //采集数据项编码
  equipmentCode: "重点设备类型:", //重点设备类型
};
const dataCodeAnalyzeMapping = reactive({
  id: "", //主键
  analyzeId: "",
  analyzeName: "", //映射值(分析项名称)
  analyzeType: "",
  deviceName: "", //设备名称
  dataCode: "",
  dataName: "",
  enterpriseId: "",
  projectId: ""
});
const getEquipmentNameList = () => {
  // 获取企业列表
  getNameList().then((res) => {
    res.data.forEach((item) => {
      equipmentNameIdMap.baseData[item.enterpriseCode] = item;
    })
    getOptions()
    getDataCodeAnalyzeMapping({id:form.dataId}).then((res) => {
      if (res.status === 200) {
        if (res.data.analyzeType === "1") {
          form.mappingValue = res.data.analyzeName
        } else {
          form.mappingValue = res.data.analyzeName
          form.deviceName = res.data.analyzeId
        }
        dataCodeAnalyzeMapping.id = form.dataId
      }else {
        //获取出错
        ElMessage.error("获取信息失败，请联系管理员！");
      }
    });
  });
}


const getOptions = () => {

  if (form.equipmentCode === "00") {
    // 通过企业信息里的项目id获取项目分析列表
    getProjectAnaListBypProjectId({id: equipmentNameIdMap.baseData[form.enterpriseCode].enterpriseId})
      .then((res) => {
        if (res.status === 200) {
          let tempData = res.data;
          let list = []
          for (let item in tempData) {
            let temp = {
              key: item,
              value: tempData[item]
            }
            list.push(temp)
          }
          options.value = list;
        }

      })
      .catch((msg) => {
        console.log(msg);
      });
  } else {
    //设备options
    selectB({"enterpriseCode": form.enterpriseCode})
        .then((res) => {
          emitData.deviceOption = res.data;
          priseData(deviceOption)
        })
        .catch((msg) => {
          console.log(msg);
          //获取出错
          ElMessage.error("获取信息失败，请联系管理员！");
        });
  }
}
const priseData = (data) => {
  formInline.id = data.id;
  formInline.label = data.label;
  formInline.name = data.name;
  formInline.region = data.region;
  formInline.weight = data.weight;
};
const deviceChange = (data) =>{
  getOptions2(data)
  for(let i=0;i<emitData.deviceOption.length;i++){
    let tempData = emitData.deviceOption[i]
    for(let j=0;j<tempData.device.length;j++){
      if(tempData.device[j].deviceId === data){
        dataCodeAnalyzeMapping.analyzeName = tempData.device[j].name
        dataCodeAnalyzeMapping.deviceName = tempData.device[j].name
        return
      }
    }
  }
}
const getOptions2 = (data) =>{
  getDeviceAnaListByDeviceId({id:data}).then((res) => {
    if (res.status === 200) {
      let tempData = res.data;
      let list = []
      for (let item in tempData) {
        let temp = {
          key: item,
          value: tempData[item]
        }
        list.push(temp)
      }
      deviceOptions.value = list;
    }
  })
}

const submitForm = async (formEl) => {
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 主键
      dataCodeAnalyzeMapping.id = form.dataId;
      // 采集配置项id
      dataCodeAnalyzeMapping.dataCode = form.dataCode;
      // 采集配置项名称
      dataCodeAnalyzeMapping.dataName = form.collectitemName;
      // 社会信用代码
      dataCodeAnalyzeMapping.enterpriseId = form.enterpriseCode;
      // 项目id
      dataCodeAnalyzeMapping.projectId = equipmentNameIdMap.baseData[form.enterpriseCode].enterpriseId;
      // 设备类型
      // 如果equipmentCode==="00",说明是项目分析,否则是设备分析
      dataCodeAnalyzeMapping.analyzeType = form.equipmentCode === "00" ? "1" : "2";
      // 分析项id
      // 项目分析不需要映射项id，设备分析需要映射项id(设备id)
      dataCodeAnalyzeMapping.analyzeId = form.equipmentCode === "00" ? "" : form.deviceName;
      // 映射值
      dataCodeAnalyzeMapping.analyzeName = form.mappingValue;
      console.log(dataCodeAnalyzeMapping)
      //验证成功,开始进行数据的更新或者新增
      if (form.mappingValue !== "" && form.mappingValue !== undefined) {
        saveDataCodeAnalyzeMapping(dataCodeAnalyzeMapping).then((res) => {
          if (res.status === 200) {
            ElMessage.success("保存成功！");
            mitts.emit("getData_1");
            form.mappingValue = null;
            dataCodeAnalyzeMapping.deviceName = null;
            dialogFormVisible.value = false;
          }else {
            ElMessage.error("保存失败！");
          }
        })
      } else {
        ElMessage.warning("请检查数据完整性！");
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
const open = () =>{
  ElMessageBox( {
    title:'删除绑定',
    message: '确定删除该绑定吗？',
    showCancelButton:true,
    showConfirmButton:true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    delDataCodeAnalyzeMapping(dataCodeAnalyzeMapping).then((res) => {
      if (res.status === 200) {
        ElMessage.success("删除成功！");
        form.mappingValue = null
        dialogFormVisible.value = false;
        mitts.emit("getData_1");
      }else {
        ElMessage.error("删除失败！");
      }
    })
  })
}

mitts.on("visible_1", (e) => {
  dialogFormVisible.value = e;
})
//接收到实体请求
mitts.on("enterprise_1", (e) => {
  title.value = "数据映射";
  form = reactive(e);
  isEdit.value = true;
  getEquipmentNameList()

});

</script>

<style lang="scss" scoped>

</style>